<?php

namespace App\Http\Controllers;

use App\Models\Area;
use App\Models\Car;
use App\Models\Complaint;
use App\Models\Consensus;
use App\Models\Cts;
use App\Models\Flow;
use App\Models\Gdp;
use App\Models\Guide;
use App\Models\Hotel;
use App\Models\Itinerary;
use App\Models\Monitor;
use App\Models\Notice;
use App\Models\Restaurant;
use App\Models\Rural;
use App\Models\Scene;
use App\Models\SceneInfo;
use App\Models\Shop;
use App\Models\Spot;
use App\Models\Team;
use App\Models\Type;
use Carbon\Carbon;
use Illuminate\Support\Facades\Input;

class OperationController extends AuthController
{

    public function index(){
        $flow_count = Flow::getTotalFlow(null,'day',Flow::max('date'));
        $team_count = Team::getTodayTeamCount();
        $team_person = Team::getTodayPersonCount();
        $scene = Scene::where('is_docking',1)->get(['type_id','cover','title','address','latlng','level','scene_area']);
        $cts = Cts::all(['title','level','latlng','address','cover']);
        $hotel = Hotel::all(['title','level','address','tel','latlng']);
        foreach ($hotel as $val){
            $val->level = $val->level?config('options.hotel_star')[$val->level]:'';
        }
        foreach ($cts as $val){
            $val->level = $val->level?config('options.cts_level')[$val->level]:'';
        }
        foreach ($scene as $val){
            $val->type_id = Type::find($val->type_id)->title;
            $val->level = config('options.scene_level')[$val->level];
        }
        return response()->json([
            'flow'=>$flow_count,
            'team'=>[
                'count'=>$team_count,
                'person'=>$team_person
            ],
           'scene'=>$scene,
            'cts'=>$cts,
            'hotel'=>$hotel
        ]);
    }
    public function baseData(){
        $scene_rate = Scene::groupWithCount('type_id');
        foreach ($scene_rate as $val){
            $val->type_id = Type::find($val->type_id)->title;
        }
        $cts_rate = Cts::groupWithCount('level');
        foreach ($cts_rate as $val){
            $val->level = $val->level!=null?config('options.cts_level')[$val->level]:'暂无信息';
        }
        $hotel_rate = Hotel::groupWithCount('level');
        foreach ($hotel_rate as $val){
            $val->level = $val->level!=null?config('options.hotel_star')[$val->level]:'暂无信息';
        }
        $guide_rate = Guide::groupWithCount('languages');
        foreach ($guide_rate as $val){
            $val->languages = config('options.guides_languages')[$val->languages];
        }
        $province_rate = Guide::groupByProvince();
        return response()->json([
            'scene_rate'=>$scene_rate,
            'cts_rate'=>$cts_rate,
            'hotel_rate'=>$hotel_rate,
            'guide_rate'=>$guide_rate,
            'province_rate'=>$province_rate
        ]);
    }

    public function ctsHotLine(){
        $lines = Itinerary::where('status',1)->take(5)->orderByRaw('num*1 desc')->get(['title','num']);
        return response()->json($lines);
    }

    public function teamNumTrend(){
        $data = Team::teamNumTrend();
        return response()->json($data);
    }

    public function merchantContrast(){

        return response()->json([
            '特产商店'=>SceneInfo::sum('shop'),
            '餐饮'=>SceneInfo::sum('restaurant'),
            '住宿'=>SceneInfo::sum('hotel'),
            '游乐设施'=>SceneInfo::sum('amusement'),
        ]);
    }

    public function sceneResources(){

        return response()->json([
            '闸机'=>SceneInfo::sum('gate'),
            '摄像头'=>SceneInfo::sum('camera'),
            '车船'=>SceneInfo::sum('vav'),
            '停车场'=>SceneInfo::sum('carpark'),
            '厕所'=>SceneInfo::sum('toilet'),
        ]);
    }

    public function sceneCategory(){
        return response()->json(
            Scene::where('is_docking',1)->get(['id','title','latlng'])
        );
    }
    public function mapPoint($scene_id=null){
        $today = Carbon::today()->toDateString();
        $yesterday = Carbon::yesterday()->toDateString();
        $type = request()->type;
        $where = $scene_id==null?[]:[['scene_id',$scene_id]];
        $flow_today = Flow::getTotalFlow($scene_id);
        $flow_yesterday = Flow::getTotalFlow($scene_id,'day',$yesterday);
        $list = Spot::where($where)->where('type',$type)->get();
        foreach ($list as $val){

            $val->cover!=null&&$val->cover = 'http://112.74.55.125:8686/storage/'.$val->cover;
        }
        return response()->json([
            'category'=>config('options.map_point_type'),
            'flow'=>[
                'today'=>$flow_today,
                'yesterday'=>$flow_yesterday
            ],
            'teams'=>[
                'today'=>Team::where('arrive_date',$today)->count(),
                'yesterday'=>Team::where('arrive_date',$yesterday)->count()
            ],
            'data'=>$list
        ]);
    }

    public function typeRate(){
        return response()->json([
            'scenes'=>Scene::count(),
            'cts'=>Cts::count(),
            'hotel'=>Hotel::count(),
            'car'=>Car::count(),
            'rurals'=>Rural::count()
        ]);
    }

    public function spots(){
        $groupByLevel = Scene::groupWithCount('level')->map(function ($val){
            return [
                "level"=>config('options.scene_level')[$val->level],
                "count"=> $val->count
            ];
        });
        $groupByArea = Scene::groupWithCount('area_id')->map(function ($val){
            return [
                "area"=>Area::find($val->area_id)->title,
                "count"=> $val->count
            ];
        });
        $groupByType = Scene::groupWithCount('type_id')->map(function ($val){
            return [
                "type"=>Type::find($val->type_id)->title,
                "count"=> $val->count
            ];
        });
        return response()->json([
            'groupByLevel'=>$groupByLevel,
            'groupByArea'=>$groupByArea,
            'groupByType'=>$groupByType
        ]);
    }

    public function cts(){
        $groupByArea = Cts::groupWithCount('area_id')->map(function ($val){
            return [
                "area"=>$val->area_id?Area::find($val->area_id)->title:'',
                "count"=> $val->count
            ];
        });
        $groupByLevel = Cts::groupWithCount('level')->map(function ($val){
            return [
                "area"=>config('options.cts_level')[$val->level],
                "count"=> $val->count
            ];
        });
        return response()->json([
            'groupByArea'=>$groupByArea,
            'groupByLevel'=>$groupByLevel,
        ]);
    }

    public function hotel(){
        $groupByLevel = Cts::groupWithCount('level')->map(function ($val){
            return [
                "area"=>config('options.hotel_star')[$val->level],
                "count"=> $val->count
            ];
        });
        $groupByArea = Cts::groupWithCount('area_id')->map(function ($val){
            return [
                "area"=>$val->area_id?Area::find($val->area_id)->title:'',
                "count"=> $val->count
            ];
        });
        return response()->json([
            'groupByLevel'=>$groupByLevel,
            'groupByArea'=>$groupByArea
        ]);
    }

    public function restaurant(){
        $groupByType = Restaurant::get(['type','num'])->map(function ($val){
            return ['type'=>config('options.restaurant_type')[$val->type],'total'=>$val->num];
        });
        $groupByArea = SceneInfo::select('restaurant','scene_id')->get()->map(function ($val){
            return ['area'=>Scene::find($val->scene_id)->area->title,'num'=>$val->restaurant];
        })->groupBy('area')->map(function ($val){
            return $val->sum('num');
        });
        return response()->json([
            'groupByType'=>$groupByType,
            'groupByArea'=>$groupByArea
        ]);
    }

    public function guides(){
        $groupByLevel = Guide::groupWithCount('level')->map(function ($val){
            return [
                "level"=>config('options.guide_level')[$val->level],
                "count"=> $val->count
            ];
        });
        $groupBySex = Guide::groupWithCount('sex')->map(function ($val){
            return [
                "sex"=>config('options.sex')[$val->sex],
                "count"=> $val->count
            ];
        });
        $groupByArea = Guide::select('id_code')->get()->map(function ($val){
            return get_source($val->id_code)->county;
        })->groupBy(function ($val){
            return $val;
        })->map(function ($val){
            return $val->count();
        });
        $groupByLanguage = Guide::groupWithCount('languages')->map(function ($val){
            return [
                "languages"=>config('options.guides_languages')[$val->languages],
                "count"=> $val->count
            ];
        });

        return response()->json([
            'groupByType'=>$groupByLevel,
            'groupByArea'=>$groupByArea,
            'groupBySex'=>$groupBySex,
            'groupByLanguage'=>$groupByLanguage
        ]);
    }

    public function cars()
    {
        $groupByArea = Car::groupWithCount('area_id')->map(function ($val){
            return [
                "area"=>$val->area_id?Area::find($val->area_id)->title:'',
                "count"=> $val->count
            ];
        });
        $groupByScope=Car::groupWithCount('scope')->map(function ($val){
            $scope = collect(explode(',',$val->scope))->map(function ($val){
                return $val!=''?config('options.car_scope')[$val]:'';
            });
            return [
                "scope"=>implode(',',$scope->toArray()),
                "count"=> $val->count
            ];
        });;
        return response()->json([
            'groupByScope'=>$groupByScope,
            'groupByArea'=>$groupByArea,
        ]);
    }

    public function merchant(){
        $list = SceneInfo::select(['restaurant','hotel','amusement','shop','scene_id'])->get()->map(function ($val){
            return [
                'scene'=>Scene::find($val->scene_id)->title,
                'restaurant'=>$val->restaurant,
                'hotel'=>$val->hotel,
                'amusement'=>$val->amusement,
                'shop'=>$val->shop,
            ];
        });
        $rate = [
            'restaurant'=>SceneInfo::sum('restaurant'),
            'hotel'=>SceneInfo::sum('hotel'),
            'amusement'=>SceneInfo::sum('amusement'),
            'shop'=>SceneInfo::sum('shop'),
        ];

        return response()->json([
            'list'=>$list,
            'rate'=>$rate,
        ]);
    }

    public function shoppingMall(){
        //$year = Input::has('year')?Input::get('year'):Carbon::now()->year;
        $list = Shop::select(['type','num'])->get()->map(function ($val){
            return [
                'type'=>config('options.shop_type')[$val->num],
                'num'=>$val->num,
            ];
        });
        return response()->json($list);
    }

    public function gdp(){
        $travel_gdp = Gdp::where('type',1)->orderByRaw('year*1')->get(['year','year_on_year','gdp']);
        $proportion = Gdp::orderByRaw('year*1')->get(['gdp','year','type'])->groupBy('year')->map(function ($val){
            $new = $val->map(function ($val){
                return $val->gdp;
            });
            return round($new[1]/$new[0],2);
        });
        $type0 = Gdp::where('year',Carbon::now()->year)->where('type',0)->first()->gdp;
        $type1 = Gdp::where('year',Carbon::now()->year)->where('type',1)->first()->gdp;
        return response()->json([
            'travel_gdp'=>$travel_gdp,
            'proportion'=>$proportion,
            'rate'=>[
                '旅游产业'=>(int)$type1,
                '其他'=>$type0-$type1
            ]
        ]);
    }

    public function complaint(){
        $groupByDays = Complaint::groupWithCount('time')->sortBy('time');
        $groupByType = Complaint::groupWithCount('target');
        $list = collect(config('options.credit_module'))->each(function ($type,$key)use ($groupByType){
            foreach ($groupByType as $v){
                if(!in_array($key,$groupByType->pluck('target')->toArray())){
                    $groupByType->put($groupByType->count(),['target'=>$key,'count'=>0]);//['target'=>$key,'count'=>0]
                }
            }
        });
        return response()->json([
            'count'=>Complaint::count(),
            'handled'=>Complaint::where('status',2)->count(),
            'today'=>Complaint::where('time',Carbon::today()->toDateString())->count(),
            'month'=>Complaint::where('time','>=',Carbon::now()->startOfMonth())->count(),
            'year'=>Complaint::where('time','>=',Carbon::now()->startOfYear())->count(),
            'groupByDays'=>$groupByDays,
            'groupByType'=>$groupByType,
        ]);
    }

    public function complaintQuestion(){

        if(Input::has('start')&&Input::has('end')){
            $star = Input::get('start');
            $end = Input::get('end');
            $complaint = Complaint::whereBetween('time',[$star,$end])->get(['status','time','target'])->map(function ($val){
                return [
                    'status'=>$val->status!=0?'handled':'unhandle',
                    'time'=>$val->time,
                    'target'=>config('options.credit_module')[$val->target],
                ];
            })->groupBy('status');
        }else{
            $complaint = Complaint::where('status',0)
                ->orWhere('status',2)
                ->get(['status','time','target','cause'])
                ->map(function ($val){
                    return [
                        'status'=>$val->status!=0?'handled':'unhandle',
                        'time'=>$val->time,
                        'target'=>config('options.credit_module')[$val->target],
                        'cause'=>$val->cause,
                        ];
                })
                ->groupBy('status');
        }
        if($complaint->count()==1){
            $complaint->put('unhandle',[]);
        }
        return response()->json($complaint);
    }

    public function dynamic(){
        $new_notice = Notice::where('type',2)->orderByDesc('updated_at')->first();
        $consensus = Consensus::all()->groupBy('type');
        return response()->json([
            'new_notice'=>$new_notice,
            'list'=>$consensus
        ]);
    }

    public function get_dynamic_point(){
        $scene_id = Input::get('scene_id');
        if($scene_id){
            $where = $scene_id==0?[]:[['scene_id',$scene_id]];
            $points = Spot::where('type',6)->where($where)->get();
            return response()->json($points);
        }else
            return response()->json(false);
    }

    public function set_dynamic_point(){
        $scene_id = Input::get('scene_id');
        $latlng = Input::get('latlng');
        $title = Input::get('title');
        if($scene_id&&$latlng){
            Spot::create([
                'scene_id'=>$scene_id,
                'type'=>6,
                'latlng'=>$latlng,
                'title'=>$title
            ]);
            return response()->json(true);
        }else
            return response()->json(false);
    }


}
